package com.coderbean.demo.action;


import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;

import com.coderbean.demo.service.EsRepository;
import org.apache.http.HttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.nio.entity.NStringEntity;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.coderbean.demo.entity.EsModel;
import com.coderbean.demo.util.FreemarkUtil;

@RestController
@RequestMapping("es")
public class EsAction {
	
	public static final Logger logger = LoggerFactory.getLogger(EsAction.class);
	
	@Autowired
	private EsRepository esRepository;
	
	@Resource
	private RestClient client;

	@PostMapping("save")
	public JSONObject save(@RequestBody EsModel esModel) {
		esRepository.save(esModel);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("success", true);
		return jsonObject;
	}
	
	@GetMapping("query")
	public JSONObject query(@RequestParam("name") String name,
			@RequestParam(name = "page", defaultValue = "0") Integer page,
			@RequestParam(name = "size", defaultValue = "10") Integer size) {
		Map<String, Object> params = new HashMap<>();
		params.put("name", name);
		params.put("size", size);
		params.put("from", page * size);
		String querySql = FreemarkUtil.parseTpl("EsQuery", params);
		Request request = new Request("GET", "/mysite/_search");
		HttpEntity entity = new NStringEntity(querySql, ContentType.APPLICATION_JSON);
		request.setEntity(entity);
		Response response;
		try {
			response = client.performRequest(request);
			String result = EntityUtils.toString(response.getEntity());
			JSONObject json = JSON.parseObject(result);
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("success", true);
			jsonObject.put("data", json);
			return jsonObject;
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("success", false);
		return jsonObject;
	}
	
}
